package com.yida.service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSException;
import com.yida.bean.blogUser;
import com.yida.dao.Mapper;
import com.yida.dao.userMapper;
import com.yida.util.utilOss;


@Service
public class serveruserImpl implements serveruser{

	@Autowired
	public  userMapper mapper;
	
	@Autowired
    private JavaMailSender mailSender;
	
	@Autowired
	private StringRedisTemplate stringRedisTemplate;

	
	
	@Override
	public blogUser selectuser(Integer id) {
		// TODO Auto-generated method stub
		return mapper.selectuser(id);
	}


	@Transactional
	@Override
	public String fileup(Integer id, MultipartFile file,HttpSession session) {
		// TODO Auto-generated method stub
		//上传判断
		boolean pd = true;
		
		//获取阿里云连接
		OSS ossClient = utilOss.getOss();
		//获取文件名
		String ordname = file.getOriginalFilename();
		//获取文件路径
		String filename = getname(ordname,id);
		//上传头像
		 try {
			ossClient.putObject(utilOss.bucketname, filename,new ByteArrayInputStream(file.getBytes()));
		} catch (OSSException | ClientException | IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();		
			pd = false;
			
		}
		 
		if (pd) {
			mapper.updateuser(id, utilOss.suffer_url+"/"+filename);
			
			//更改session里面的信息
			blogUser user =  (blogUser) session.getAttribute("user");
			user.setImgUrl(utilOss.suffer_url+"/"+filename);
			session.setAttribute("user", user);
			
			return utilOss.suffer_url+"/"+filename;
		} else {
			return "false";
		}
		 
		
		
		
	}
	
	//获取文件名
	private String getname(String ordname,Integer id) {
		
		//获取文件后窜
		   	String suffix = ordname.substring(ordname.lastIndexOf("."));
		//前窜
			String prefix = "user/headimg/";   
    	
    	//为了避免图片重名 使用uuid命名图片
    	String uuid = UUID.randomUUID().toString().replace("-", "");
    			
    	//组合filename
    	String filename =  prefix+id+"/"+uuid+suffix;
    	
		return filename;
    	
	}


	//更正头像地址
	@Override
	public boolean imgUpdate(Integer id, String url,HttpSession session) {
		// TODO Auto-generated method stub
		
		if (mapper.updateuser(id, url) > 0) {
			//更改session里面的信息
			blogUser user =  (blogUser) session.getAttribute("user");
			user.setImgUrl(url);
			session.setAttribute("user", user);
			
			return true;
		}else {
			return false;
		}
		
	}


	@Override
	public boolean emailyzm(Integer id, String email) {
		
		//生成5位验证码
		String yzmString = "";
		for (int i = 0; i < 5; i++) {
			int yan= (int)( Math.random()*9+1);
			yzmString = yzmString + String.valueOf(yan);
		}
   

		// TODO Auto-generated method stub
		SimpleMailMessage message  = new SimpleMailMessage();
		//谁发的
		message.setFrom("1320123744@qq.com");
		 //谁要接收
	    message.setTo(email);
	    //邮件标题
	    message.setSubject("Smile验证码");
	    //邮件内容
	    message.setText("您正在绑定邮箱，验证码为:"+yzmString+",切勿将验证码泄露于他人,本条验证码有效期为15分钟。");
	    
	    try {
	        mailSender.send(message);
	        if ( stringRedisTemplate.opsForList().size("email") > 0) {
				stringRedisTemplate.delete("email");
			}
	        stringRedisTemplate.opsForList().rightPushAll("email",id.toString(),email,yzmString);
	        stringRedisTemplate.expire("email", 60*15, TimeUnit.SECONDS);
	        
	        return true;
	      } catch (Exception e) {
	        e.printStackTrace();
	        return false;
	      }
	    
	
	    
	}


	//验证邮箱的验证码
	@Transactional
	@Override
	public boolean emailyzmyz(Integer id, String email, String emailcode) {
		// TODO Auto-generated method stub
		List<String> redis  = stringRedisTemplate.opsForList().range("email", 0, -1);
	
		String redisId = redis.get(0);
		String redisEmail= redis.get(1);
		String redisEmailCode = redis.get(2);
		
		if (redisId.equals(id.toString()) && redisEmail.equals(email) && redisEmailCode.equals(emailcode) ) {
		    Integer result = mapper.updateEmail(id, email);
		    if (result > 0) {
				return true;
			}
		}
		
		return false;
	}


	@Override
	public blogUser pwdemail(Integer id) {
		
		// TODO Auto-generated method stub
		return mapper.selectuser(id);
	}


	@Override
	public Integer updateUserAll(blogUser user) {
		// TODO Auto-generated method stub
		
		return mapper.updateUserAll(user);
	}
	

}
